package com.mhy.view;
/**
 * Created by mahongyin on 2021/11/3.
 *
 * @author mahongyin
 * @date 2021/11/3 17:56
 * 手指缩放textview
 */

import android.content.Context;
import android.content.pm.PackageManager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatTextView;

public class TouchScaleTextView extends AppCompatTextView {
    private int mode = 0;
    private float mOldDist = 0f;
    private float mTextSize = 0f;

    public TouchScaleTextView(Context context) {
        super(context);
    }

    public TouchScaleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TouchScaleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mTextSize == 0f) {
            mTextSize = getTextSize();
        }
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                mOldDist = 0f;
                mode = 1;
            }
            break;
            case MotionEvent.ACTION_UP: {
                mode = 0;
            }
            break;
            case MotionEvent.ACTION_POINTER_UP: {
                mode -= 1;
            }
            break;
            case MotionEvent.ACTION_POINTER_DOWN: {
                mOldDist = spacing(event);
                mode += 1;
            }
            break;
            case MotionEvent.ACTION_MOVE: {
                if (mode >= 2) {
                    float newDist = spacing(event);
                    if (Math.abs(newDist - mOldDist) > 50) {
                        zoom(newDist / mOldDist);
                        mOldDist = newDist;
                    }
                }
            }
            break;
            default:
                break;
        }
        return true;
    }

    private void zoom(float f) {
        mTextSize *= f;
        setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
    }

    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getX(0) - event.getX(1);
        return (float) Math.sqrt((double) (x * x + y * y));
    }

    /**
     * 多点触控需要硬件支持 检测方法
     */
    public boolean isSupportMultiTouch(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH);
    }
}
